from flask import Blueprint, request, jsonify
from sqlalchemy import desc
from model.company import Company
from model.job import Job
from model.province_city import ProvinceCity
from model.user import User
from service.company_service import CompanyService
from service.job_classes_service import JobClassesService
from service.job_servie import JobService
from service.province_service import ProvinceService
from service.user_collection_service import UserCollectionService
from service.user_deliver_service import UserDeliverStatusService
from utils.securtiy import login_required, get_user_id
from utils.tools import json_response
from utils.work_db import get_session
from utils.work_log import get_logger

log = get_logger(__name__)
api = Blueprint('job_api', __name__, url_prefix='/api/v1/job')


@api.route('/list', methods=['POST'])
def _list():
    session = get_session()
    args = request.json
    q = session.query(Job, Company, ProvinceCity, User)
    q = q.join(Company, Job.company_id == Company.company_id)
    q = q.join(ProvinceCity, ProvinceCity.code == Job.city_code)
    q = q.outerjoin(User, User.user_id == Job.create_userid)
    page = args.get('page', 1)
    page_size = args.get('page_size', 20)
    total_number = q.count()
    total_page = total_number // page_size + 1
    q = q.order_by(desc(Job.job_id))
    q = q.offset((page - 1) * page_size)
    q = q.limit(page_size)
    result = []
    for d in q.all():
        result.append(
            {
                'job_id': d.Job.job_id,
                'job_name': d.Job.job_name,
                'company_name': d.Company.name,
                'city_name': d.ProvinceCity.name,
                'real_name': d.User and d.User.real_name,
                'mobile': d.User and d.User.mobile
                # 'country_name': d.ProvinceCity.name
            }
        )
    return jsonify({'code': 0, 'data': result,
                    'page_info': {
                        'total_number': total_number,
                        'total_page': total_page,
                        'page': page,
                        'page_size': page_size
                    }
                    })


@api.route('/get_province', methods=['POST', 'GET'])
def get_province():
    """
    获得城市信息
    :return:
    """
    session = get_session()
    service = ProvinceService(session)
    data_list = service.list_all()
    result = {"dataList": data_list}
    return json_response(result, msg='', code=1)


@api.route('/job_list', methods=['POST'])
@login_required
def job_list(**kwargs):
    """
    获得职位列表
    工作类型(1:兼职 2:全职,3:全部)
    {
    "page":"0",
    "job_type":"1",
    "province_code":"",
    "city_code":"",
    "job_class":"",
    "job_post":"",
    "key":"",
    "country_code":"",
    "lat":"",
    "lon":"",
    "limit":""
    }
    """
    params = request.json
    province_code = key = city_code = job_class = job_post = country_code = None
    page = 0
    job_type = None
    limit = 10
    user_id = get_user_id()
    # 页码
    if params and params.get("page"):
        page = int(params.get("page"))
    # 工作类型(1:兼职 2:全职,3:全部)
    if params and params.get("job_type"):
        job_type = params.get("job_type")
    # 省份
    if params and params.get("province_code", "0"):
        province_code = params.get("province_code")
    # 城市id
    if params and params.get("city_code", "0"):
        city_code = params.get("city_code")
    if params and params.get("job_class", "0"):
        job_class = params.get("job_class")
    if params and params.get("job_post", "0"):
        job_post = params.get("job_post")
    if params and params.get("country_code", "0"):
        country_code = params.get("country_code")
    # 检索关键字
    if params and params.get("key"):
        key = params.get("key")

    if params and params.get("limit"):
        limit = int(params.get("limit"))

    session = get_session()
    try:
        service = JobService(session)
        result = service.query_job(province_code=province_code,
                                   city_code=city_code,
                                   key=key,
                                   job_type=job_type,
                                   job_class=job_class,
                                   job_post=job_post,
                                   country_code=country_code,
                                   page=page,
                                   limit=limit, user_id=user_id)
        return json_response(result, msg='', code=1)
    except Exception as e:
        log.error("job_list:" + str(e))


@api.route('/get_job/<job_id>', methods=['GET'])
@login_required
def get_job(job_id, **kwargs):
    """
    职位详情
    :param job_id:
    :param kwargs:
    :return:
    """
    user_id = get_user_id()
    session = get_session()
    service = JobService(session)
    company_service = CompanyService(session)
    collection_service = UserCollectionService(session)
    deliver_service = UserDeliverStatusService(session)
    data = {}
    job_json = service.get_job_detail(job_id=job_id)
    if not job_json or not job_json["company_id"]:
        return json_response(data, msg='职位信息存在错误', code=-1)

    data["job"] = job_json
    company = company_service.get_by_company_id(job_json["company_id"])
    if company:
        data["company"] = company.json()

    resume_record = deliver_service. \
        get_send_records(user_id=user_id,
                         job_id=job_id)
    collection_ok = collection_service. \
        get_collection_by_job_uid(job_id=job_id, user_id=user_id)

    # 是否投递过简历
    if resume_record:
        data["sent_resume"] = '1'
    else:
        data["sent_resume"] = '0'
    # 是否收藏
    if collection_ok:
        data["collected"] = '1'
    else:
        data["collected"] = '0'

    return json_response(data, msg='', code=1)


@api.route('/get_header_job', methods=['GET', 'POST'])
@login_required
def get_header_job(**kwargs):
    from model.sys_dict import SysDict
    """
    头图地址
    :param kwargs:
    :return:
    """
    session = get_session()

    header_dict = session.query(SysDict).filter(SysDict.key == 'header_banner').first()

    job_id = header_dict.value
    job = session.query(Job).filter(Job.job_id == job_id).first()
    if job:
        data = {"job_id": job_id}
        return json_response(data, msg='', code=1)
    else:
        return json_response('', msg='', code=-1)


@api.route('/get_job_class', methods=['GET'])
def get_job_class():
    """

    :return:
    """
    data = {}
    session = get_session()
    try:
        service = JobClassesService(session)
        classes = service.get_classes()
        if classes:
            data["dataList"] = classes
        return json_response(data, msg='', code=1)
    finally:
        session.close()
